<template>
  <el-tabs
    type="card"
    :value="currentPath"
    :before-leave="onTabClick"
    @tab-remove="onTabRemove"
  >
    <el-tab-pane
      :closable="tab.path !== '/dashboard'"
      v-for="tab in tabs"
      :key="tab.path"
      :label="tab.label"
      :name="tab.name"
    >
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import { ADD_TABS, DELETE_TABS, SET_CURRENT_PATH } from "../store/types";

export default {
  name: "ZTabs",
  computed: {
    ...mapGetters(["tabs", "currentPath"]),
  },
  methods: {
    ...mapMutations([ADD_TABS, DELETE_TABS, SET_CURRENT_PATH]),
    onTabClick(tab) {
      console.log("tabs-path", tab);
      if (this.$route.path !== tab) {
        this.$router.push(tab);

        this[SET_CURRENT_PATH](tab);
      }
    },
    onTabRemove(path) {
      if (path === this.currentPath) {
        const index = this.tabs.findIndex((tab) => tab.path === path);
        if (index !== -1) {
          const currentPath = this.tabs[index - 1].path;
          this[SET_CURRENT_PATH](currentPath);
          this.$router.push(currentPath);
        }
      }
      this[DELETE_TABS]({ path });
    },
  },
  watch: {
    $route: {
      immediate: true,
      handler(route) {
        // console.log(route);
        this[SET_CURRENT_PATH](route.path);
        this[ADD_TABS]({
          label: route.meta.title,
          path: route.path,
          name: route.path,
          componentName:
            route.matched[route.matched.length - 1].components.default.name,
        });
      },
    },
  },
};
</script>

<style scoped></style>
